package posecco.client;

import java.util.Date;

import posecco.shared.FieldUtil;
import posecco.shared.Util;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.rpc.AsyncCallback;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Login extends FlowPanel {

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final LoginServiceAsync loginService = GWT.create(LoginService.class);

	final FieldUtil fieldUtil = new FieldUtil();
	final Button sendButton;

	public Login() {
		
		fieldUtil.addFormTextField(this, "login");
		fieldUtil.addFormPwdField(this, "pwd");
		sendButton = new Button(Util.getMessage("sendButtonLabel"));
		add(sendButton);
		
		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText(Util.getMessage("remoteCall"));
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button(Util.getMessage("closeButtonLabel"));
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		
		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				sendDataToServer();
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendDataToServer() {
				// First, we validate the input.
				final String login = fieldUtil.getFieldValue("login");
				final String pwd = Util.getHash(fieldUtil.getFieldValue("pwd"));
				fieldUtil.removeErrorMessages();
				sendButton.setEnabled(false);
				serverResponseLabel.setText("");
				loginService.loginServer(login, pwd, new AsyncCallback<String>() {
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
						dialogBox
								.setText(Util.getMessage("remoteCallFailed") + ": " + caught.getMessage());
						serverResponseLabel
								.addStyleName("serverResponseLabelError");
						dialogBox.center();
						closeButton.setFocus(true);
					}
	
					public void onSuccess(String result) {
						try {	
							if (result != null) {
								dialogBox.setText(Util.getMessage("remoteCall"));
								serverResponseLabel
										.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(Util.getMessage("loginSuccess"));
								dialogBox.center();
			            		final long DURATION = 1000 * 60 * 60 * 24 * 14; //duration remembering login. 2 weeks in this example.
			            		Date expires = new Date(System.currentTimeMillis() + DURATION);
			            		Cookies.setCookie("sid", result, expires, null, "/", false);
								PoSecCo.getInstance().loginUserBySessionId(result);
								closeButton.setFocus(true);
							}
							else {
								dialogBox
										.setText(Util.getMessage("loginFail"));
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel
										.setText(Util.getMessage("loginError"));
								dialogBox.center();
								closeButton.setFocus(true);
							}
						}
						catch (NullPointerException e) {
							dialogBox
									.setText(Util.getMessage("loginFail"));
							serverResponseLabel
									.addStyleName("serverResponseLabelError");
							serverResponseLabel
									.setText(Util.getMessage("loginError"));
							dialogBox.center();
							closeButton.setFocus(true);
						}
					}
				});
			}
		}


		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
	}
}